package com.best.intelligentTrolley

import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.view.View.OnLongClickListener
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.best.intelligentTrolley.model.ParamSettingInfoModel
import com.best.intelligentTrolley.serial_port.KTDataUtils
import com.best.intelligentTrolley.serial_port.SerialPortCommand
import com.best.intelligentTrolley.serial_port.SerialPortManager
import com.best.intelligentTrolley.utils.CommonUtils
import com.best.intelligentTrolley.widget.GradientTextView
import com.best.intelligentTrolley.widget.TextBanner
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import java.util.*
import kotlin.concurrent.timer

class MainActivity : AppCompatActivity(), SerialPortManager.OnSerialPortDataListener {

    private var timerCountDown: CountDownTimer? = null
    private var timeTimer:Timer? = null
    private var runTime:Int = 0
    private var tv_battery:TextView? = null

    private var humidity:String = "--"
    private var temperature:String = "--"
    private var pm25:String = "--"
    private var tvoc:String = "--"

    private var tv_banner: TextBanner? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        SerialPortManager.instance.addOnSerialPortDataListener(this)

        tv_battery = findViewById(R.id.tv_battery)
        val ibtn_dis_time_left = findViewById<ImageButton>(R.id.ibtn_dis_time_left)
        val et_dis_time = findViewById<EditText>(R.id.et_dis_time)
        val ibtn_dis_time_right = findViewById<ImageButton>(R.id.ibtn_dis_time_right)
        val bg_dising = findViewById<View>(R.id.bg_dising)
        val tv_count_down = findViewById<GradientTextView>(R.id.tv_count_down)
        val tv_stop_dis = findViewById<TextView>(R.id.tv_stop_dis)
        val tv_start_dis = findViewById<TextView>(R.id.tv_start_dis)
        val tv_date = findViewById<TextView>(R.id.tv_date)
        val rg_speed = findViewById<RadioGroup>(R.id.rg_speed)
        val tv_info = findViewById<TextView>(R.id.tv_info)
        val iv_machine = findViewById<ImageView>(R.id.iv_machine)

        tv_banner = findViewById(R.id.tv_banner)

        tv_date.text = TimeUtils.millis2String(System.currentTimeMillis(), TimeUtils.getSafeDateFormat("MM/dd HH:mm"))
        tv_count_down.typeface = Typeface.createFromAsset(assets,"fonts/countdown.ttf")

        ibtn_dis_time_left?.setOnClickListener {
            if(et_dis_time?.text.toString().toInt()>0){
                et_dis_time?.setText((et_dis_time?.text.toString().toInt()-1).toString())
            }
        }
        ibtn_dis_time_right?.setOnClickListener {
            et_dis_time?.setText((et_dis_time?.text.toString().toInt()+1).toString())
        }
        tv_start_dis.setOnClickListener {
            bg_dising.visibility = View.VISIBLE
            tv_count_down.visibility = View.VISIBLE
            tv_stop_dis.visibility = View.VISIBLE

            var speed = 40
            when(rg_speed.checkedRadioButtonId){
                R.id.rbtn_low ->{
                    speed = SPUtils.getInstance().getInt("speedLow",40)
                }
                R.id.rbtn_mid ->{
                    speed = SPUtils.getInstance().getInt("speedMid",60)
                }
                R.id.rbtn_high ->{
                    speed = SPUtils.getInstance().getInt("speedHigh",80)
                }
            }

            SerialPortCommand.mainModuleCMD.openPlasma()
            SerialPortCommand.fanModuleCMD.openDegradationFan(KTDataUtils.intToHex(speed))

//            SerialPortManager.instance.sendStringData(SerialPortCommand.mainModuleCMD.build())
            SerialPortManager.instance.sendStringData(SerialPortCommand.fanModuleCMD.build())

            timerCountDown = object :CountDownTimer(et_dis_time.text.toString().toInt()*60*1000L,1000){
                override fun onTick(millisUntilFinished: Long) {
                    runTime = ((et_dis_time.text.toString().toInt()*60*1000L-millisUntilFinished)/1000).toInt()
                    val second = millisUntilFinished / 1000
                    val m = (second / 60).toInt()
                    val s = second % 60
                    tv_count_down.text = "${if (m < 10) "0" else ""}${m}:${if (s < 10) "0" else ""}${s}"
                }

                override fun onFinish() {
                    bg_dising.visibility = View.GONE
                    tv_count_down.visibility = View.GONE
                    tv_stop_dis.visibility = View.GONE

                    stopDis()
                }
            }

            timerCountDown?.start()
        }
        tv_stop_dis.setOnClickListener {
            timerCountDown?.cancel()
            bg_dising.visibility = View.GONE
            tv_count_down.visibility = View.GONE
            tv_stop_dis.visibility = View.GONE

            stopDis()
        }
        tv_info.setOnClickListener {
            startActivity(Intent(this,InfoActivity::class.java))
        }
        iv_machine.setOnLongClickListener {
            startActivity(Intent(this@MainActivity, SettingActivity::class.java))
            true
        }
        var showDatas:ArrayList<String> = ArrayList()
        showDatas.add("温度 ${temperature}℃")
        showDatas.add("湿度 ${humidity}%RH")
        showDatas.add("PM2.5 $pm25")
        showDatas.add("TVOC $tvoc")

        tv_banner?.setData(showDatas)
        tv_banner?.startAnimation()

        timeTimer = timer(null, false, 1000L, 1000L) {
            runOnUiThread {
                tv_date.text = TimeUtils.millis2String(System.currentTimeMillis(), TimeUtils.getSafeDateFormat("MM/dd HH:mm"))
            }
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainModuleCMD.build())
            SerialPortManager.instance.sendStringData(SerialPortCommand.QUERY_TEMPERATURE_HUMIDITY)
            SerialPortManager.instance.sendStringData(SerialPortCommand.QUERY_PM25)
        }

        try {
            val path = CommonUtils.getCacheFolder() + "config.txt"
            if (FileUtils.isFileExists(path)) {
                val data = FileIOUtils.readFile2String(path)
                val paramSettingInfo = Gson().fromJson(data, ParamSettingInfoModel::class.java)

                SPUtils.getInstance().put("factory_no",paramSettingInfo?.FactoryNumber)
                SPUtils.getInstance().put("company_name",paramSettingInfo?.CompanyName)
                SPUtils.getInstance().put("company_tel",paramSettingInfo?.Phone)
                SPUtils.getInstance().put("company_address",paramSettingInfo?.Address)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        SerialPortManager.instance.sendStringData(SerialPortCommand.QUERY_DEVICE_VERSION)
    }

    private fun stopDis(){
        Config.addPlasmaModuleUsageTime(runTime)

        SerialPortCommand.mainModuleCMD.closePlasma()
        SerialPortCommand.fanModuleCMD.closeDegradationFan()

//        SerialPortManager.instance.sendStringData(SerialPortCommand.mainModuleCMD.build())
        SerialPortManager.instance.sendStringData(SerialPortCommand.fanModuleCMD.build())

    }

    override fun onDataReceived(text: String) {
        Log.e("TAG", "onDataReceived: :$text")
        val array = text.split(" ")
        if (array[0] == "7E" && array[1] == "7E") {
            val id = array[2]
            val cmd = array[3]

            when(id){
                "10" ->{
                    when(cmd){
                        "57" ->{//获取主控版本号
                            App.instance.zkVersion =
                                "${KTDataUtils.hexToInt(array[7])}.${KTDataUtils.hexToInt(array[8])}.${KTDataUtils.hexToInt(array[9])}.${
                                    KTDataUtils.hexToInt(array[10])
                                }"
                        }
                        "13" ->{//电池信息
                            val batteryTemperature = array[4]//电池温度
                            val electricity = KTDataUtils.hexToInt(array[5])//电池电量
                            runOnUiThread {
                                tv_battery?.text = "$electricity%"
                            }
                        }
                    }
                }
                "A0" ->{
                    if (cmd == "A1") {
                        if (array.size >= 6) {
                            temperature = KTDataUtils.hexToSignedInt(array[4]).toString()
                            humidity = KTDataUtils.hexToInt(array[5]).toString()
                            pm25 = KTDataUtils.hexToInt(array[6]+array[7]).toString()
                            tvoc = KTDataUtils.hexToInt(array[8]+array[9]).toString()

                            var showDatas:ArrayList<String> = ArrayList()
                            showDatas.add("温度 ${temperature}℃")
                            showDatas.add("湿度 ${humidity}%RH")
                            showDatas.add("PM2.5 ${pm25}μg/m3")
                            showDatas.add("TVOC ${tvoc}ppm")
                            runOnUiThread {
                                tv_banner?.refreshData(showDatas)
                            }
                        }
                    }
                }
            }
        }
    }



    override fun onDestroy() {
        super.onDestroy()
        timeTimer?.cancel()
    }

}